package org.gdufe.books.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.gdufe.pojos.dto.InsertBookDto;
import org.gdufe.pojos.dto.PageParams;
import org.gdufe.books.mapper.BookMapper;
import org.gdufe.pojos.pojo.Book;
import org.gdufe.pojos.pojo.Log;
import org.gdufe.pojos.vo.R;
import org.gdufe.books.service.BookService;
import org.gdufe.pojos.vo.PageResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 根据条件查询书籍--分页
     * @param title
     * @return
     */
    @Override
    public PageResponseResult querryBooks(String title, PageParams pageParams) {
        if (pageParams==null||pageParams.getPageNo()<=0||pageParams.getPageSize()<=0){
            pageParams=new PageParams();
        }
        QueryWrapper<Book> wrapper=new QueryWrapper<Book>();
        if (title!=null&&!title.isEmpty()){
            wrapper.like("title",title);
        }
        //分页对象
        Page<Book> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        IPage<Book> pageResult = bookMapper.selectPage(page, wrapper);

        // 获取数据列表
        List<Book> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResponseResult result=new PageResponseResult((int) pageResult.getCurrent(), (int) pageResult.getSize(), (int) pageResult.getTotal());
        result.setData(list);
        return result;
    }

    //添加图书
    @Override
    public R insertBook( InsertBookDto insertBookDto) {
        Book book=new Book();
        Integer number = insertBookDto.getNumber();
        String title = insertBookDto.getTitle();
        if(number==null||number<=0){
            return R.errorResult(500,"输入大于0的数量");
        }
        if(title==null||title.isEmpty()){
            return R.errorResult(500,"请输入书籍名称");
        }
        book.setImg(insertBookDto.getImg());
        book.setTitle(title);
        book.setPoint(10.0);
        book.setNumber(number);

        int insert = bookMapper.insert(book);
        if (insert<=0){
            return R.errorResult(500,"插入失败");
        }
        return R.okResult(200,"插入成功");
    }

    //todo 禁止多次借出
    //借书
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R borrow(Integer id,String username) {
        Book book = bookMapper.selectById(id);
        if (book==null){
            return R.errorResult(500,"书籍不存在或已下架");
        }
        Integer number = book.getNumber();
        if (number<=0){
            return R.errorResult(500,"书籍已无库存");
        }
        book.setNumber(number-1);
        int i = bookMapper.updateById(book);
        if (i<=0){
            return R.errorResult(500,"借出失败");
        }
        //发送mq消息记录log
        String destination = "createBorrowLogMsg";

        Log log = new Log();
        log.setBId(id);
        log.setUsername(username);
        log.setTitle(book.getTitle());
        log.setBorrowTime(LocalDateTime.now());
        String payload = JSON.toJSONString(log);
        System.out.println("【payload】="+payload);
        SendResult sendResult = rocketMQTemplate.syncSend(destination, payload);
        System.out.println("【同步发送结果】:"+ sendResult);
        if (sendResult.getSendStatus()== SendStatus.SEND_OK){
            return R.okResult(200,"成功借出");
        }else {
            throw new RuntimeException("日志消息发送失败");
        }

    }


    //归还 --bookID
    @Transactional(rollbackFor = Exception.class)
    public R returnBook(Integer id,String username){
        Book book = bookMapper.selectById(id);
        if (book==null){
            return R.errorResult(500,"书籍不存在或已下架");
        }
        Integer number = book.getNumber();
        book.setNumber(number+1);
        int i = bookMapper.updateById(book);
        if (i<=0){
            return R.errorResult(500,"归还失败");
        }
        //发送mq消息记录log
        String destination = "createReturnLogMsg";

        Log log = new Log();
        log.setBId(id);
        log.setUsername(username);
        log.setTitle(book.getTitle());
        log.setReturnTime(LocalDateTime.now());
        String payload = JSON.toJSONString(log);
        System.out.println("【payload】="+payload);
        SendResult sendResult = rocketMQTemplate.syncSend(destination, payload);
        System.out.println("【同步发送结果】:"+ sendResult);
        if (sendResult.getSendStatus()== SendStatus.SEND_OK){
            return R.okResult(200,"成功归还");
        }else {
            throw new RuntimeException("日志消息发送失败");
        }
    }

    @Override
    public R querryTops() {
        QueryWrapper<Book> wrapper=new QueryWrapper<>();
        wrapper.orderByDesc("point");
        wrapper.last("limit 10");
        List<Book> books = bookMapper.selectList(wrapper);
        return R.okResult(books);
    }

    @Override
    public R listBId() {
        QueryWrapper<Book> wrapper=new QueryWrapper<>();
        wrapper.select("id").orderByAsc("id");
        List<Book> books = bookMapper.selectList(wrapper);
        List<Integer> collect = books.stream().map(a -> {
            return a.getId();
        }).collect(Collectors.toList());
        for (Integer id:collect ) {
            System.out.println(id);
        }
        return R.okResult(collect);
    }

    @Override
    public R deleteBook(Integer id) {
        if (id<=0){
            return R.errorResult(500,"参数错误");
        }
        QueryWrapper<Book> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        int i = bookMapper.delete(wrapper);
        if (i<=0){
            return R.errorResult(500,"删除失败");
        }
        return R.okResult(200,"删除成功");
    }

    @Override
    public R updateBook(Book book) {
        String title = book.getTitle();
        Integer number = book.getNumber();
        Double point = book.getPoint();
        if (title==null||number==null||point==null||title.isEmpty()||number<0||point<0||point>10){
            return R.errorResult(500,"参数错误，请输入正确的参数");
        }
        int i = bookMapper.updateById(book);
        if (i<=0){
            return R.errorResult(500,"更新失败");
        }
        return R.okResult(200,"更新成功");
    }

    //更新分数
    @Override
    @Transactional
    public R updatePoint(Integer id, Double point) {
        Book book = bookMapper.selectById(id);
        if (book==null){
            return R.errorResult(500,"目标书籍不存在");
        }
        book.setPoint(point);
        int i = bookMapper.updateById(book);
        if (i<=0){
            return R.errorResult(500,"更新分数失败");
        }
        return R.okResult(200,"更新分数成功");
    }

}
